package com.example.administrator.shzs.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.example.administrator.shzs.R;
import com.example.administrator.shzs.adapter.IntegralXrecycleviewAdapter;
import com.example.administrator.shzs.entity.Integral;
import com.example.administrator.shzs.parse.ParseIntegral;
import com.example.administrator.shzs.ui.IntegraItemItemActivity;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.utils.RecyclviewTopBtton;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


/**
 * 积分兑换 Fragment
 */
public class IntegralFragment extends Fragment {

    @Bind(R.id.No_Data_show)
    LinearLayout NoDataShow;
    private ProgressBar progressbar;
    private ImageView imageView;

    private XRecyclerView IntergraXecycleView;
    private IntegralXrecycleviewAdapter adapter;
    private List<Integral> datalist = new ArrayList<>();
    private List<Integral> templist = new ArrayList<>();

    private int page = 1;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_integral, null);
        //初始化
        setViews(view);

        //初始化IImageLoader
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));


        IntergraXecycleView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                iniDataFromWeb();
            }

            @Override
            public void onLoadMore() {
                page++;
                iniDataFromWeb();
            }
        });

        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        iniDataFromWeb();
    }


    private void setViews(View view) {
        IntergraXecycleView = (XRecyclerView) view.findViewById(R.id.IntergraXecycleView);

        progressbar = (ProgressBar) view.findViewById(R.id.progressbar);
        imageView = (ImageView) view.findViewById(R.id.network);
        IntergraXecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        IntergraXecycleView.setLoadingMoreProgressStyle(ProgressStyle.SquareSpin);
        IntergraXecycleView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //IntergraXecycleView Item 间隔
        RecyclviewTopBtton recyclviewTopBtton = new RecyclviewTopBtton(10);
        IntergraXecycleView.addItemDecoration(recyclviewTopBtton);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);


            switch (msg.what) {

                case 0:

                    if (datalist.size() == 0) {
                        progressbar.setVisibility(View.GONE);
                        imageView.setVisibility(View.GONE);
                        NoDataShow.setVisibility(View.VISIBLE);//没有数据展示
                    }
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            iniDataFromWeb();
                            progressbar.setVisibility(View.VISIBLE);
                            NoDataShow.setVisibility(View.GONE);//没有数据隐藏
                        }
                    });

                    IntergraXecycleView.loadMoreComplete();
                    IntergraXecycleView.refreshComplete();

                    break;
                case 1:

                    progressbar.setVisibility(View.GONE);
                    NoDataShow.setVisibility(View.GONE);//没有数据隐藏

                    adapter = new IntegralXrecycleviewAdapter(datalist, getActivity());
                    IntergraXecycleView.setAdapter(adapter);
                    IntergraXecycleView.refreshComplete();


                    adapter.setIntegralItem(new IntegralXrecycleviewAdapter.IntegralItem() {
                        @Override
                        public void Onclik(View view, int postion) {
                            Intent intent = new Intent(getActivity(), IntegraItemItemActivity.class);
                            Integral data = datalist.get(postion);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("Integral", data);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }
                    });

                    break;
                case 2:
                    datalist.addAll(templist);
                    adapter.notifyDataSetChanged();
                    templist.clear();

                    IntergraXecycleView.loadMoreComplete();

                    break;
            }
        }
    };

    /**
     * 从网络获取地址并解析
     */
    private void iniDataFromWeb() {

        if (datalist.size() == 0) {
            progressbar.setVisibility(View.VISIBLE);
        } else {
            progressbar.setVisibility(View.GONE);
        }

        String url = Contents.INDEX_INTEGRAL + page;
        Request request = new Request.Builder().url(url).build();
        Contents.okhttp.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                handler.sendEmptyMessage(0);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String request = response.body().string();
                if (page == 1) {
                    datalist = ParseIntegral.getIntegral(request);
                    if (datalist.size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }

                } else {
                    templist = ParseIntegral.getIntegral(request);
                    if (templist.size() > 0) {
                        handler.sendEmptyMessage(2);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            }

        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
